/*
 * Tencent is pleased to support the open source community by making QMUI_Android available.
 *
 * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the MIT License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/MIT
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sansan.ultrasound_handpad.fragment.home;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.text.Html;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.qmuiteam.qmui.layout.QMUIFrameLayout;
import com.qmuiteam.qmui.skin.QMUISkinHelper;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.skin.QMUISkinValueBuilder;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;
import com.qmuiteam.qmui.widget.QMUICollapsingTopBarLayout;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.popup.QMUIFullScreenPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.sansan.ultrasound_handpad.QDMainActivity;
import com.sansan.ultrasound_handpad.R;
import com.sansan.ultrasound_handpad.adaptor.brvah.PcbTaskPositionRecordAdapter;
import com.sansan.ultrasound_handpad.base.BaseFragment;
import com.sansan.ultrasound_handpad.base.MmkvManager;
import com.sansan.ultrasound_handpad.convertor.JsonConverter;
import com.sansan.ultrasound_handpad.entity.PcbScanProductResult;
import com.sansan.ultrasound_handpad.entity.PcbTaskPositionRecord;
import com.sansan.ultrasound_handpad.entity.PcbTaskPositionRecordDetail;
import com.sansan.ultrasound_handpad.entity.StaffEntity;
import com.sansan.ultrasound_handpad.entity.request.PcbTaskPosRecordRequestA;
import com.sansan.ultrasound_handpad.fragment.components.viewpager.QDLazyTestObserver;
import com.yanzhenjie.kalle.JsonBody;
import com.yanzhenjie.kalle.Kalle;
import com.yanzhenjie.kalle.simple.SimpleCallback;
import com.yanzhenjie.kalle.simple.SimpleResponse;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author cginechen
 * @date 2016-10-19
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener{
    private final static String TAG = HomeFragment.class.getSimpleName();

//    QDRecyclerViewAdapter mRecyclerViewAdapter;
    private TextToSpeech tts;

    private Button homefragment_feeding_rButton;
    private MediaPlayer mediaPlayer = new MediaPlayer();

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.collapsing_topbar_layout)
    QMUICollapsingTopBarLayout mCollapsingTopBarLayout;
    @BindView(R.id.topbar)
    QMUITopBar mTopBar;
    @BindView(R.id.homefragment_feeding_rButton)
    QMUIRoundButton mFeedingBtn;

    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    LinearLayoutManager mPagerLayoutManager;
    PcbTaskPositionRecordAdapter mAdapter;
    private StaffEntity staffEntity = null;
    private String mPcbTaskCode = null;
    private String mProductCode = null;
    private PcbTaskPositionRecordDetail pcbTaskPositionRecordDetail;

    private List<PcbTaskPositionRecordDetail> processList = null;

    private int flag = 0;
    private boolean isPopUpShow = false;
    private TextView showResult = null;
    private QMUIFullScreenPopup mQmuiFullScreenPopup = null;

    private Timer timer = null;
    private TimerTask timerTask = null;
    private Context context = null;
    private int statu = 0;

    private void startTimerTask() {
        stopTimerTask();

        if (timer == null) {
            timer = new Timer();
        }
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
//                    for (PcbTaskPositionRecordDetail pcbTaskPositionRecordDetail : processList) {
//                        if(pcbTaskPositionRecordDetail.getInstall_status() != "1"){
//                            scanProductCode(mProductCode, mPcbTaskCode);
//                        }
//                    }
                    //testInstallStatus(pcbTaskPositionRecordDetail);
                    /*if (showResult.getVisibility() == View.INVISIBLE){

                    }*/
                    scanProductCode(mProductCode, mPcbTaskCode);
                }
            };
        }
        timer.schedule(timerTask, 0, 3000L);
    }

    private void stopTimerTask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

//    @Override
//    public void onAttach(@NonNull Context context) {
//        super.onAttach(context);
//        registerEffect(this, new QMUIFragmentMapEffectHandler() {
//            @Override
//            public boolean shouldHandleEffect(@NonNull MapEffect effect) {
//                return effect.getValue("interested_type_key") != null;
//            }
//
//            @Override
//            public void handleEffect(@NonNull MapEffect effect) {
//                Object value = effect.getValue("interested_value_key");
//                if(value instanceof String){
//                    Toast.makeText(context, ((String)value), Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
//
//        registerEffect(this, new QMUIFragmentEffectHandler<CustomEffect>() {
//            @Override
//            public boolean shouldHandleEffect(@NonNull CustomEffect effect) {
//                return true;
//            }
//
//            @Override
//            public void handleEffect(@NonNull CustomEffect effect) {
//                Toast.makeText(context, effect.getContent(), Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void handleEffect(@NonNull List<CustomEffect> effects) {
//               // we can only handle the last effect.
//               handleEffect(effects.get(effects.size() - 1));
//            }
//        });
//    }

//    //设置监听器 也就是实例化接口
//    public void setOnClickListener(final OnOKClickListener clickListener) {
//        this.mClickListener = clickListener;
//    }


    @Override
    protected View onCreateView() {
        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_home, null);
        Button btn = rootView.findViewById(R.id.homefragment_feeding_rButton);
        btn.setOnClickListener(this);
        //try {
            //File file = new File(Environment.getExternalStorageDirectory(), "finish.mp3");
            //mediaPlayer.setDataSource(file.getPath()); // 指定音频文件的路径

            //todo
            //mediaPlayer = MediaPlayer.create(context,R.raw.finish);
            //mediaPlayer.start();
            //btn.setOnClickListener(this);
        //} catch (Exception e) {
            //e.printStackTrace();
        //}
        //initMediaPlayer();
        ButterKnife.bind(this, rootView);
        //
        initTopBar();
        //
        if (mFeedingBtn != null) {
            mFeedingBtn.setVisibility(View.GONE);
        }
        //
        initAdapter();
        mPagerLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mPagerLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        /*设置空白布局*/
        mAdapter.setEmptyView(getScanNumView());

        mCollapsingTopBarLayout.setScrimUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Log.i(TAG, "scrim: " + animation.getAnimatedValue());
            }
        });

        mCollapsingTopBarLayout.addOnOffsetUpdateListener(new QMUICollapsingTopBarLayout.OnOffsetUpdateListener() {
            @Override
            public void onOffsetChanged(QMUICollapsingTopBarLayout layout, int offset, float expandFraction) {
                Log.i(TAG, "offset = " + offset + "; expandFraction = " + expandFraction);
            }
        });
        return rootView;
    }

    private void initMediaPlayer() {
        try {
            //File file = new File(Environment.getExternalStorageDirectory(), "finish.mp3");
            //mediaPlayer.setDataSource(file.getPath()); // 指定音频文件的路径

            context = getContext();
            mediaPlayer = MediaPlayer.create(context,R.raw.finish);

            mediaPlayer.prepare(); // 让MediaPlayer进入到准备状态
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取IP地址
     */
    private String obtainIP() {
        return MmkvManager.getInstance().getMMKV().decodeString("PAD_IP", "http://192.168.0.192:8756/");
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        if (mAdapter == null) {
            mAdapter = new PcbTaskPositionRecordAdapter();
            mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    if (view.getId() == R.id.pcb_taskposition_record_rv_item_cb) {
                        Toast.makeText(getActivity(), "勾选了第" + position + "个", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }



    /**
     * 扫描工号的界面
     */
    private View getScanNumView() {

        flag = 0;

        if (mCollapsingTopBarLayout != null) {
            mCollapsingTopBarLayout.setTitle("扫描工号");
        }
        View errorView = getLayoutInflater().inflate(R.layout.scanning_worknum_layout, mRecyclerView, false);
        errorView.findViewById(R.id.scanning_worknum_rButton).setOnClickListener(v -> {
            Toast.makeText(getActivity(), "点击了员工扫码按钮", Toast.LENGTH_SHORT).show();
            try {
                //File file = new File(Environment.getExternalStorageDirectory(), "finish.mp3");
                //mediaPlayer.setDataSource(file.getPath()); // 指定音频文件的路径

                //todo
                mediaPlayer = MediaPlayer.create(context,R.raw.finish);
                mediaPlayer.start(); // 让MediaPlayer进入到准备状态
            } catch (Exception e) {
                e.printStackTrace();
            }
            //getScanNumView();
//            // todo 此处需要做判断是否点击了按钮 实现点击扫码按钮时才执行扫码操作获取员工工号,不点击扫码按钮时扫码无效(即不调用获取员工工号接口)
//            Toast.makeText(getActivity(), "扫描工号", Toast.LENGTH_SHORT).show();   //点击按钮执行扫码操作
//            // todo 这里执行扫员工工号二维码
           /*调用登录接口*/
           loginWebPage();
        });

        return errorView;
    }

    /**
     * 扫描获取程序信息界面
     */
    private View getScanCodeView() {

        flag = 1;
        if (staffEntity == null){
            getScanNumView();
        }

        if (mCollapsingTopBarLayout != null) {
            mCollapsingTopBarLayout.setTitle("欢迎:" + (staffEntity == null ? "" : staffEntity.getNickname()));
        }



        View errorView = getLayoutInflater().inflate(R.layout.scanning_code_obtainrecrd_layout, mRecyclerView, false);

        errorView.findViewById(R.id.scanning_code_obtainrecord_rButton).setOnClickListener(v -> {
            Toast.makeText(getActivity(), "点击了程序扫码按钮", Toast.LENGTH_SHORT).show();
            //getScanCodeView();
            //Toast.makeText(getActivity(), "扫码获取程序信息界面", Toast.LENGTH_SHORT).show();
            /*获取程序信息*/
            obtainPcbTaskPostionRecord(null, null, null);
        });


        return errorView;
    }

    /**
     * 登录接口
     */
    public void loginWebPage() {
        Kalle
                .post(obtainIP() + "login")
                .param("username", "admin")
                .param("password", "123456")
                .tag(this)
                .perform(new SimpleCallback<String>() {
                    @Override
                    public void onResponse(SimpleResponse<String, String> response) {
                        if (response.isSucceed()) {
                            /*登录成功切回页面*/
                            if (mAdapter != null) {
                                mAdapter.setEmptyView(getScanCodeView());
                            }
                        }
                        Log.d(TAG, "onResponse: " + response.succeed());
                    }
                });
    }

    /**
     * 从服务器获取程序信息
     */
    public void obtainPcbTaskPostionRecord(String deviceCode, String pcbId, String pcbTaskCode) {
        JSONObject object = null;
        try {
            object= new JSONObject();
            object.put("deviceCode", deviceCode);
            object.put("pcbId", pcbId);
            object.put("processTaskCode", pcbTaskCode);
//            object.put("pcbTaskCode", pcbTaskCode);
//            object.put("deviceCode", "B15002");
//            object.put("pcbId", "DCY2.908.1444GS-RB");
//            object.put("processTaskCode", "WORK014083");
        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }

        Kalle
                .post(obtainIP() + "PcbTaskPositionRecord/buildPositionRecordAndReturn")
                .body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<PcbTaskPositionRecord>() {
                    @Override
                    public void onResponse(SimpleResponse<PcbTaskPositionRecord, String> response) {
                        // todo 此处有异常
                        try {
                            Log.d(TAG, "obtainPcbTaskPostionRecord_onResponse: " + response.succeed());
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        if (response.isSucceed()) {
                            if (mAdapter != null) {
                                if (mAdapter.hasEmptyView()) {
                                    mAdapter.removeEmptyView();
                                    //mAdapter.setEmptyView(deviceCode,pcbTaskCode);
                                }
                                //todo ?  闪退问题  (猜测: 与扫描程序二维码的时间有关)
                                PcbTaskPositionRecord record = response.succeed();
                                if (record.getDetailList() != null && record.getDetailList().size() > 0) {
                                    if (processList == null) {
                                        processList = new ArrayList<>(response.succeed().getDetailList());
                                    } else {
                                        processList.clear();
                                        processList.addAll(response.succeed().getDetailList());
                                    }
                                    mAdapter.setNewData(processList);
                                    if (mFeedingBtn != null) {
                                        mFeedingBtn.setVisibility(View.VISIBLE);
                                    }
                                    flag = 2; //进入程序列表显示界面
                                    startPositonRecord(pcbTaskCode,staffEntity.getNickname());
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 扫描物料编码通知上料
     */

    private void testInstallStatus (PcbTaskPositionRecordDetail pcbTaskPositionRecordDetail){
        if (pcbTaskPositionRecordDetail.getInstall_status() != "1"){
            scanProductCode(mProductCode,mPcbTaskCode);
        }
    }
    private void scanProductCode(final String productCode, String pcbTaskCode) {
        JSONObject object = null;
        try {
            object= new JSONObject();
            object.put("productCode", productCode);
            object.put("processTaskCode", pcbTaskCode);
        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }

        /*if (!showResult.getText().toString().contains("上料中")){
            System.out.println(11);;
        }*/

            Kalle
                    .post(obtainIP() + "PcbTaskPositionRecord/scanProductCode")
                    .body(new JsonBody(object.toString()))
                    .converter(new JsonConverter())
                    .tag(this)
                    .perform(new SimpleCallback<PcbScanProductResult>() {
                        @Override
                        public void onResponse(SimpleResponse<PcbScanProductResult, String> response) {
                            Log.d(TAG, "扫描飞达料盘: " + response.succeed());

                            //if (showResult.getText().toString().trim().equals("")){}
                            //if (TextUtils.isEmpty(msg)){
                                if (response.isSucceed()) {
                                    int finishSize = 0;
                                    PcbTaskPositionRecordDetail param = null;

                                    for (PcbTaskPositionRecordDetail detail : processList) {
                                        if ("2".equals(detail.getInstall_status())) {
                                            finishSize++;
                                        }
                                        if (!TextUtils.isEmpty(productCode) && productCode.equals(detail.getProduct_code())) {
                                            param = detail;
                                            continue;
                                        }
                                    }

                                    PcbScanProductResult result = response.succeed();
                                    int totalSize = mAdapter.getData().size();
                                    if (!isPopUpShow) {
                                        if (totalSize <= finishSize) {
                                            //Toast.makeText(getActivity(), "上料结束！", Toast.LENGTH_SHORT).show();
                                            //showResult.setText("上料结束");
                                            //showResult.setTextColor(Color.rgb(255,255,0));
                                            //showResult.setTextSize(52);
                                            finishPositonRecord(pcbTaskCode);
                                            fullScreenPopupWindow(HomeFragment.this.getView(), param);
                                            //showResult.setText("上料结束\n请点击下方按钮关闭");

                                            stopTimerTask();
                                        } else if (param != null && "2".equals(param.getInstall_status())) {
                                            Toast.makeText(getActivity(), "工序" + param.getPosition() + "—— 该物料已插入", Toast.LENGTH_SHORT).show();
                                            stopTimerTask();
                                        } else {
                                            fullScreenPopupWindow(HomeFragment.this.getView(), param);
                                        }
                                    } else if (showResult != null) {
                                        /*if (showResult.isShown() == false){
                                            System.out.println(11);
                                        }*/
//                                        System.out.println(showResult.getText().toString().substring(4));
//
//                                        if (param.getPosition() != null){
//                                        }
//                                        System.out.println(param.getPosition());
//                                        System.out.println(param.getPosition().equals(showResult.getText().toString().substring(4)));
                                        //showResult.getVisibility() == View.INVISIBLE;
                                        if (param.getPosition() != null && param.getPosition().equals(showResult.getText().toString().substring(4))){
                                            if (totalSize <= finishSize) {
                                                showResult.setTextColor(Color.rgb(255,255,0));
                                                showResult.setTextSize(60);
                                                showResult.setText("上料结束");
                                                //stopTimerTask();

                                                //fullScreenPopupWindow(HomeFragment.this.getView(), param);
                                            } else if (param == null) {
                                                showResult.setTextColor(Color.rgb(255,0,0));
                                                showResult.setText("不在程序中");
                                                //stopTimerTask();
                                            } else if ("1".equals(result.getStatus()) && param.getInstall_status() != "2") {

                                                try {
                                                    if (statu == 0){
                                                        //todo
                                                        mediaPlayer = MediaPlayer.create(getContext(),R.raw.shangliao);

                                                        //mediaPlayer.prepare();// 让MediaPlayer进入到准备状态
                                                        mediaPlayer.start();
                                                        statu = 1;
                                                    }

                                                    //mediaPlayer.setLooping(false);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                                // showResult.getVisibility() == View.GONE;

                                                showResult.setTextSize(52);
                                                showResult.setTextColor(Color.rgb(0, 255, 0));
                                                //showResult.setText("上料结束\n请点击下方按钮关闭");
                                                showResult.setText("上料中\n" + param.getPosition());
                                                //if (showResult.isShown()){
                                                //continue;
                                                //}
                                                //String msg = showResult.getText().toString().trim();
                                                //if (!TextUtils.isEmpty(msg)){
                                                //return;
                                                //}
                                                //onInit(TextToSpeech.SUCCESS);
                                                //tts.speak("abcd",TextToSpeech.QUEUE_ADD,null);


                                                //showResult.setText(Html.fromHtml(("上料中"+ "\n" + "<font size=\"200\">" + param.getPosition() + "<font>")));
                                                //Toast.makeText(getActivity(), "上料结束！", Toast.LENGTH_SHORT).show();
                                                //showResult.setText("上料结束");
                                            } else if ("2".equals(result.getStatus())) {
                                                //showResult.setText("上料结束\n请点击下方按钮关闭");
                                                try {
                                                    if (statu == 1){
                                                        //todo
                                                        mediaPlayer = MediaPlayer.create(getContext(),R.raw.finish);
                                                        //mediaPlayer.prepare();// 让MediaPlayer进入到准备状态
                                                        mediaPlayer.start();
                                                        //mediaPlayer.setLooping(false);
                                                        statu = 0;
                                                    }

                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                                int pos = mAdapter.getData().indexOf(param);
                                                PcbTaskPositionRecordDetail find = mAdapter.getItem(pos);
                                                find.setInstall_status("2");
                                                mAdapter.notifyDataSetChanged();

                                                if (mQmuiFullScreenPopup != null) {
                                                    mQmuiFullScreenPopup.dismiss();
                                                }

                                                //String msg = showResult.getText().toString().trim();
                                                //if (!TextUtils.isEmpty(msg)){
                                                //continue;
                                                //}

                                            }
                                        }
                                        else {
                                            try {
                                                param.getPosition();
                                            }catch (Exception e){
                                                e.printStackTrace();
                                            }

                                        }

                                    }
                                }
                            //}
                        }
                    });
        //}
    }


    private Button btnPlay;
    /**
     * 开始上料
     */
    private void startPositonRecord(String pcbTaskCode, String username) {
        JSONObject object = null;
        try {
            object= new JSONObject();
            object.put("processTaskCode", pcbTaskCode);
            object.put("username", username);
        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }

        Kalle
                .post(obtainIP() + "PcbTaskPositionRecord/startPositonRecord")
                .body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<String>() {
                    @Override
                    public void onResponse(SimpleResponse<String, String> response) {
                        Log.d(TAG, "开始上料: " + response.succeed());

                        if (response.isSucceed()) {
                            Toast.makeText(getActivity(), response.succeed(), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity(), response.failed(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 结束上料
     */
    private void finishPositonRecord(String pcbTaskCode) {
        JSONObject object = null;
        try {
            object= new JSONObject();
            object.put("processTaskCode", pcbTaskCode);
        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }

        Kalle
                .post(obtainIP() + "PcbTaskPositionRecord/finishPositionRecord")
                .body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<String>() {
                    @Override
                    public void onResponse(SimpleResponse<String, String> response) {
                        Log.d(TAG, "结束上料: " + response.succeed());

                        if (response.isSucceed()) {
                            Toast.makeText(getActivity(), response.succeed(), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity(), response.failed(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 显示对话框
     */
    private void showMessageNegativeDialog() {
        new QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle("标题")
                .setMessage("确定要删除吗？")
                .setSkinManager(QMUISkinManager.defaultInstance(getContext()))
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "删除", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    /**
     * 扫码广播
     */
    /*接收扫码器传回来的扫码数据*/
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            /*扫描数据*/
            byte[] scanData = intent.getByteArrayExtra("barocode");
            /*数据长度*/
            int dataLen = intent.getIntExtra("length", 0);
            /*数据类型*/
            byte dataTyp = intent.getByteExtra("barcodeType", (byte)0);
            /*条码字符串*/
            String barcodeStr = new String(scanData, 0, dataLen);
            Log.d(TAG, "BroadcastReceiver: " + barcodeStr);
            /**
             * 獲取到工號去查詢
             */
            if (!TextUtils.isEmpty(barcodeStr)) {
                if (flag == 0) {  //获取工号
                    obtainUsrMsg(barcodeStr);
                } else if (flag == 1) { //获取程序的3个参数
                    String[] params = barcodeStr.split(";");
                    if (params == null || params.length != 3) {
                        Toast.makeText(getActivity(), "扫描获取的参数异常!", Toast.LENGTH_SHORT).show();
                    } else {
                        /*获取程序信息*/
                        mPcbTaskCode = params[2];
                        obtainPcbTaskPostionRecord(params[0], params[1], params[2]);
                    }
                } else if (flag == 2) {
//                    if (!barcodeStr.equals(mProductCode)) {
//                        isSuccess = false;
//                    }
                    mProductCode = barcodeStr;
                    /*启动定时器定时查询*/   // todo 扫物料码
                    startTimerTask();
                }

            }
        }
    };

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
        if (mFeedingBtn != null) {
            mFeedingBtn.setVisibility(View.VISIBLE);
        }
        if (flag == 2) {
            mAdapter.setEmptyView(getScanCodeView());
        } else if (flag == 1) {
            mAdapter.setEmptyView(getScanNumView());
        }
    }

    /**
     * 獲取工號
     */
    private void obtainUsrMsg(String num) {
        Kalle
                .get(obtainIP() + "PcbTaskPositionRecord/getUserInfoByCard/" + num)
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<StaffEntity>() {
                    @Override
                    public void onResponse(SimpleResponse<StaffEntity, String> response) {
                        /*登录成功切回页面*/
                        // todo
                        if (mAdapter != null && response.isSucceed()) {
                            staffEntity = response.succeed();
                            mAdapter.setEmptyView(getScanCodeView());
                        }
                    }
                });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getLazyViewLifecycleOwner().getLifecycle().addObserver(
                new QDLazyTestObserver("QDCollapsingTopBar"));
    }

    @Override
    protected boolean translucentFull() {
        return true;
    }

    private void initTopBar() {
        mCollapsingTopBarLayout.setTitle("扫描工号");

        mTopBar.addRightImageButton(R.mipmap.icon_topbar_about, R.id.topbar_right_about_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showEditTextDialog();            }
        });
    }

    /**
     * 带输入框的对话框
     */
    private void showEditTextDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        builder.setTitle("设置IP地址")
                .setSkinManager(QMUISkinManager.defaultInstance(getContext()))
                .setPlaceholder("在此输入您的IP")
                .setDefaultText(obtainIP())
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        if (MmkvManager.getInstance().getMMKV().encode("PAD_IP", builder.getEditText().getText().toString())) {
                            Toast.makeText(getActivity(), "设置成功", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), "设置失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

//    @OnClick({R.id.homefragment_feeding_rButton})
//    void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.homefragment_feeding_rButton:
//                Toast.makeText(getActivity(), "点击了上料按钮", Toast.LENGTH_SHORT).show();
//                startPositonRecord(mPcbTaskCode, staffEntity == null ? "" : staffEntity.getNickname());
//                AssetManager assetManager;
//                MediaPlayer player = null;
//                player = new MediaPlayer();
//                assetManager = getResources().getAssets();
//                try {
//                    AssetFileDescriptor fileDescriptor = assetManager.openFd("shangliao.mp3");
//                    player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getStartOffset());
//                    player.prepare();
//                    player.start();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                break;
//
//            default:
//                break;
//        }
//    }
    //对三个按钮执行点击事件才执行调用接口扫码的操作
    /*@OnClick({R.id.homefragment_feeding_rButton})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.homefragment_feeding_rButton:
                Toast.makeText(getActivity(), "点击了上料按钮", Toast.LENGTH_SHORT).show();
                startPositonRecord(mPcbTaskCode, staffEntity == null ? "" : staffEntity.getNickname());

                break;
            default:
                break;
        }
    }*/



    @Override
    public void onResume() {
        super.onResume();

        if (getActivity() == null) {
            return;
        }
        /*注册扫描器广播*/
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("urovo.rcv.message");
        getActivity().registerReceiver(this.mScanReceiver, intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();

        if (getActivity() == null) {
            return;
        }
        /*注销扫描器广播*/
        getActivity().unregisterReceiver(this.mScanReceiver);
    }

    //    @OnClick({R.id.home_scanJobNum, R.id.home_scanCode})
//    void onClick(View v) {
//        try {
//            switch (v.getId()) {
//                case R.id.home_scanJobNum:
//                    /*扫描工号*/
//                case R.id.home_scanCode:
//                    /*扫描二维码*/
//                    HomeFragment.this.startFragment(ScanFragment.class.newInstance());
//                    break;
//                default:
//                    break;
//            }
//        } catch (Exception e) {
//            Toast.makeText(getContext(), "进入界面失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
//        }
//
//    }



//    private void initTabs() {
//
//        QMUITabBuilder builder = mTabSegment.tabBuilder();
//        builder.setSelectedIconScale(1.2f)
//                .setTextSize(QMUIDisplayHelper.sp2px(getContext(), 13), QMUIDisplayHelper.sp2px(getContext(), 15))
//                .setDynamicChangeIconColor(false);
//        QMUITab component = builder
//                .setNormalDrawable(ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_component))
//                .setSelectedDrawable(ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_component_selected))
//                .setText("Components")
//                .build(getContext());
//        QMUITab util = builder
//                .setNormalDrawable(ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_util))
//                .setSelectedDrawable(ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_util_selected))
//                .setText("Helper")
//                .build(getContext());
//        QMUITab lab = builder
//                .setNormalDrawable(ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_lab))
//                .setSelectedDrawable(ContextCompat.getDrawable(getContext(), R.mipmap.icon_tabbar_lab_selected))
//                .setText("Lab")
//                .build(getContext());
//
//        mTabSegment.addTab(component)
//                .addTab(util)
//                .addTab(lab);
//    }

//    private void initPagers() {
//
//        HomeController.HomeControlListener listener = new HomeController.HomeControlListener() {
//            @Override
//            public void startFragment(BaseFragment fragment) {
//                HomeFragment.this.startFragment(fragment);
//            }
//        };
//
//        mPages = new HashMap<>();
//
//        HomeController homeComponentsController = new HomeComponentsController(getActivity());
//        homeComponentsController.setHomeControlListener(listener);
//        mPages.put(Pager.COMPONENT, homeComponentsController);
//
//        HomeController homeUtilController = new HomeUtilController(getActivity());
//        homeUtilController.setHomeControlListener(listener);
//        mPages.put(Pager.UTIL, homeUtilController);
//
//        HomeController homeLabController = new HomeLabController(getActivity());
//        homeLabController.setHomeControlListener(listener);
//        mPages.put(Pager.LAB, homeLabController);
//
//        mViewPager.setAdapter(mPagerAdapter);
//        mTabSegment.setupWithViewPager(mViewPager, false);
//    }

//    enum Pager {
//        COMPONENT, UTIL, LAB;
//
//        public static Pager getPagerFromPositon(int position) {
//            switch (position) {
//                case 0:
//                    return COMPONENT;
//                case 1:
//                    return UTIL;
//                case 2:
//                    return LAB;
//                default:
//                    return COMPONENT;
//            }
//        }
//    }

    /**
     * 全屏浮层次 带关闭按钮
     */
    private void fullScreenPopupWindow(View v, PcbTaskPositionRecordDetail detail) {
        QMUISkinValueBuilder builder = QMUISkinValueBuilder.acquire();
        QMUIFrameLayout frameLayout = new QMUIFrameLayout(getContext());
        frameLayout.setBackground(
                QMUIResHelper.getAttrDrawable(getContext(), R.attr.qmui_skin_support_popup_bg));
        frameLayout.setBackgroundColor(detail == null ? Color.RED : Color.GREEN);
        builder.background(R.attr.qmui_skin_support_popup_bg);
        QMUISkinHelper.setSkinValue(frameLayout, builder);
        frameLayout.setRadius(QMUIDisplayHelper.dp2px(getContext(), 60));
        int padding = QMUIDisplayHelper.dp2px(getContext(), 20);
        frameLayout.setPadding(padding, padding, padding, padding);

        showResult = new TextView(getContext());
        showResult.setLineSpacing(QMUIDisplayHelper.dp2px(getContext(), 4), 1.0f);
        showResult.setPadding(padding, padding, padding, padding);
        //showResult.setText(detail == null ? "不在程序中" : "上料中\n" + detail.getPosition());
        if(detail == null){
            showResult.setTextColor(Color.rgb(255,0,0));
            showResult.setTextSize(40);
            showResult.setText("物料不在程序中");
            stopTimerTask();
        } else if (detail.getInstall_status() == "2"){
            showResult.setTextColor(Color.rgb(255,255,0));
            showResult.setTextSize(60);
            showResult.setText("上料结束");
            stopTimerTask();
        } else {
            showResult.setTextColor(Color.rgb(0,255,0));
            showResult.setTextSize(52);
            showResult.setText("上料中\n" + detail.getPosition());
        }
//        showResult.setTextColor(
//                QMUIResHelper.getAttrColor(getContext(), R.attr.app_skin_common_title_text_color));
        //showResult.setTextSize(52);
        builder.clear();
        builder.textColor(R.attr.app_skin_common_title_text_color);
        QMUISkinHelper.setSkinValue(showResult, builder);
        showResult.setGravity(Gravity.CENTER);

        builder.release();

        int size = QMUIDisplayHelper.dp2px(getContext(), 200);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(size, size);
        frameLayout.addView(showResult, lp);

        mQmuiFullScreenPopup = QMUIPopups.fullScreenPopup(getContext())
                .addView(frameLayout)
                .closeBtn(true)
                .skinManager(QMUISkinManager.defaultInstance(getContext()))
                .onBlankClick(new QMUIFullScreenPopup.OnBlankClickListener() {
                    @Override
                    public void onBlankClick(QMUIFullScreenPopup popup) {
                        isPopUpShow = false;

                        Toast.makeText(getContext(), "停止轮询查询", Toast.LENGTH_SHORT).show();
                        stopTimerTask();
                    }
                })
                .onDismiss(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        isPopUpShow = false;

                        Toast.makeText(getContext(), "停止轮询查询", Toast.LENGTH_SHORT).show();
//
//                        if (isSuccess) {
//                            dd
//                        }

                        stopTimerTask();
                    }
                });
        mQmuiFullScreenPopup.show(v);

        isPopUpShow = true;
    }


    @Override
    protected boolean canDragBack() {
        return false;
    }

    @Override
    public Object onLastFragmentFinish() {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.homefragment_feeding_rButton:
                /*try {

                    mediaPlayer = MediaPlayer.create(getContext(),R.raw.shangliao);
                    mediaPlayer.start();

                } catch (Exception e) {
                    e.printStackTrace();
                }*/
                /*if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start(); // 开始播放
                }*/
                break;

            default:
                break;
        }
    }



//    @Override
//    public void onInit(int status) {
//        if (status == TextToSpeech.SUCCESS) {
//            //设置播放语言
//            int result = tts.setLanguage(Locale.CHINESE);
//            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
//                //Toast.makeText(HomeFragment.this,"不支持", Toast.LENGTH_SHORT).show();
//            }else if(result == TextToSpeech.LANG_AVAILABLE){
//                //初始化成功之后才可以播放文字
//                //否则会提示“speak failed: not bound to tts engine
//                //TextToSpeech.QUEUE_ADD会将加入队列的待播报文字按顺序播放
//                //TextToSpeech.QUEUE_FLUSH会替换原有文字
//                tts.speak("abc",TextToSpeech.QUEUE_ADD,null);
//            }
//
//        } else {
//            Log.e("TAG", "初始化失败");
//        }
//    }





    /*private SoundPool soundPool;//声明一个SoundPool
    private int soundID;//创建某个声音对应的音频ID

    @SuppressLint("NewApi")
    private void initSound() {
        soundPool = new SoundPool.Builder().build();
        soundID = soundPool.load(this, R.raw.shangliao, 1);
    }
    @SuppressLint("NewApi")
    private void initSound2() {
        soundPool = new SoundPool.Builder().build();
        soundID = soundPool.load(this, R.raw.finish, 1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.homefragment_feeding_rButton:
            case R.id.btnPlay2:
                playSound();
                break;
        }
    }*/

    /*private void playSound() {
        soundPool.play(
                soundID,
                0.1f,      //左耳道音量【0~1】
                0.5f,      //右耳道音量【0~1】
                0,         //播放优先级【0表示最低优先级】
                0,         //循环模式【0表示循环一次，-1表示一直循环，其他表示数字+1表示当前数字对应的循环次数】
                1          //播放速度【1是正常，范围从0~2】
        );
    }*/

}